package com.ledi.guns.core.util.baiduUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import com.ledi.guns.core.util.StringUtil;
import com.ledi.guns.core.util.TimeUtil;
import com.ledi.guns.core.util.baiduUtil.define.BaseState;
import com.ledi.guns.core.util.baiduUtil.define.State;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;

// import com.qcloud.cos.request.UploadFileRequest;
// import com.qcloud.cos.sign.Credentials;

/**
 * 文件名称： com.ledi.common.util.baiduUtil.Uploade.java<br/>
 * 初始作者： 崔业新<br/>
 * 创建日期： 2017年10月25日<br/>
 * 功能说明： 这里用一句话描述这个类的作用--此句话需删除 <br/>
 * =================================================<br/>
 * 修改记录：<br/>
 * 修改作者 日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (苏州乐迪教育科技有限公司-幼儿事业部) 2017-2018.All rights reserved.<br/>
 */
public class Uploade {

	// @Value("${app.access.img.type}")
	private static String[] imgTypes = { "jpg", "jpeg", "png", "bmp" };
	// @Value("${cos.appid}")
	private static long cosAppid = 1252955498L;

	// @Value("${cos.secret.id}")
	private static String cosSecretId = "AKIDITSFpD6cbprhfAomttjdR3Sft31n2Gjz";

	// @Value("${cos.secret.key}")
	private static String cosSecretKey = "GLEyVqzzRdjRxnwvlPq5uAtQoEdqu3lG";

	// @Value("${cos.region}")
	private static String cosRegion = "sh";

	// @Value("${cos.bucket.name}")
	private static String cosBucketName = "ccbucket";

	// @Value("${cos.file.root.url}")
	private static String cosFileRootUrl = "http://ccbucket-1252955498.cossh.myqcloud.com/";

	public static State uploadFile(String suffix, byte[] data) {

		COSCredentials cred = new BasicCOSCredentials(cosSecretId, cosSecretKey);
		ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
		COSClient cosclient = new COSClient(cred, clientConfig);
		String bucketName = cosBucketName + "-" + cosAppid;

		String key = createUploadLinuxPath(suffix, "file");

		String temp = FileUtils.getTempDirectoryPath();
		String url = temp + key;
		File file = BetyToFile(url);

		ExecutorService threadPool = Executors.newFixedThreadPool(32);
		// 传入一个threadpool, 若不传入线程池, 默认TransferManager中会生成一个单线程的线程池。
		TransferManager transferManager = new TransferManager(cosclient, threadPool);

		PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
		// 本地文件上传

		try {

			Upload upload = transferManager.upload(putObjectRequest);
			upload.waitForCompletion();

		} catch (CosServiceException e) {
			e.printStackTrace();
		} catch (CosClientException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			file.delete();
			transferManager.shutdownNow();
			cosclient.shutdown();
		}

		if (StringUtil.isNotEmpty(key)) {
			key = key.replace(cosFileRootUrl, "");
		}
		State storageState = new BaseState(true, null);

		if (storageState.isSuccess()) {
			storageState.putInfo("url", key);
			storageState.putInfo("type", suffix);
			storageState.putInfo("original", "");
		}
		return storageState;

	}

	private static String createUploadPath(String fileType) {

		return "/image/" + TimeUtil.getYear() + "/" + TimeUtil.getMonth() + "/" + TimeUtil.getDay() + "/" + java.util.UUID.randomUUID().toString() + "." + fileType;
	}

	public static State uploadFile(MultipartFile multipartFile) throws IOException {

		String fileName = multipartFile.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		COSCredentials cred = new BasicCOSCredentials(cosSecretId, cosSecretKey);
		ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
		COSClient cosclient = new COSClient(cred, clientConfig);
		String bucketName = cosBucketName + "-" + cosAppid;

		String key = createUploadLinuxPath(fileType, "file");

		String temp = FileUtils.getTempDirectoryPath();
		String url = temp + key;
		File file = new File(url);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		inputStreamtofile(multipartFile.getInputStream(), file);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		ExecutorService threadPool = Executors.newFixedThreadPool(32);
		// 传入一个threadpool, 若不传入线程池, 默认TransferManager中会生成一个单线程的线程池。
		TransferManager transferManager = new TransferManager(cosclient, threadPool);

		PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
		// 本地文件上传

		try {

			Upload upload = transferManager.upload(putObjectRequest);
			upload.waitForCompletion();

		} catch (CosServiceException e) {
			e.printStackTrace();
		} catch (CosClientException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			file.delete();
			transferManager.shutdownNow();
			cosclient.shutdown();
		}
		if (StringUtil.isNotEmpty(key)) {
			key = "http://ccbucket-1252955498.cossh.myqcloud.com/" + key;
		}
		State storageState = new BaseState(true, null);

		if (storageState.isSuccess()) {
			storageState.putInfo("url", key);
			// storageState.putInfo("type", suffix);
			storageState.putInfo("original", "");
		}
		return storageState;
	}

	public static boolean validateImgType(String type) {

		for (String imgType : imgTypes) {
			if (imgType.equalsIgnoreCase(type)) {
				return true;
			}
		}
		return false;
	}

	public static String createUploadLinuxPath(String fileType, String packageName) {

		return "/" + packageName + "/" + TimeUtil.getYear() + "/" + TimeUtil.getMonth() + "/" + TimeUtil.getDay() + "/"
				+ java.util.UUID.randomUUID().toString() + "." + fileType;
	}

	public static File BetyToFile(String filePath)
	{

		File file = new File(filePath);
		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
		BufferedOutputStream stream = null;
		FileOutputStream fstream = null;
		byte[] data = new byte[(int) file.length()];
		try {
			fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (stream != null) {
					stream.close();
				}
				if (null != fstream) {
					fstream.close();
				}
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return file;
	}

	public static void inputStreamtofile(InputStream ins, File file) {

		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			if (null != os) {
				os.close();
			}
			if (null != ins) {
				ins.close();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != os) {

					os.close();

				}
				if (null != ins) {
					ins.close();

				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
